/**
 * 
 */
package com.jxc.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.jxc.dao.MemberDaoI;
import com.jxc.model.po.CustomerType;
import com.jxc.model.po.Member;
import com.jxc.model.po.MemberType;
import com.jxc.model.po.User;
import com.jxc.model.vo.VMember;

/**
 * @author Tino
 * 
 */
@Repository("memberDao")
public class MemberDaoImpl implements MemberDaoI {

	@Autowired
	private SessionFactory sessionFactory;

	public List<VMember> combobox(VMember vmember) {
		Session session = this.sessionFactory.openSession();
		List<VMember> list = this.changeModelMember(this.find(vmember,session));
		session.close();
		return list;
	}

	private List<Member> find(VMember vMember,Session session) {
		String hql = "from Member t where t.isDeleted=false ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vMember, hql, values);

		Query q = session.createQuery(hql);
		if (values != null && values.size() > 0) {
			for (int i = 0; i < values.size(); i++) {
				q.setParameter(i, values.get(i));
			}
		}

		return q.list();
	}

	private List<VMember> changeModelMember(List<Member> members) {
		List<VMember> vMemberes = new ArrayList<VMember>();
		if (members != null && members.size() > 0) {
			for (Member m : members) {
				VMember vMember = new VMember();
				BeanUtils.copyProperties(m, vMember);
				if (m.getMemberType() != null) {
					MemberType type = m.getMemberType();
					vMember.setTid(type.getId());
					vMember.setTname(type.getName());
				}
				if (m.getCustomerType() != null) {
					CustomerType ct = m.getCustomerType();
					vMember.setCtId(ct.getId());
					vMember.setCtName(ct.getName());
				}
				if (m.getUser() != null) {
					User user = m.getUser();
					vMember.setUid(user.getId());
					vMember.setUname(user.getUsername());
				}
				vMemberes.add(vMember);
			}
		}
		return vMemberes;
	}

	private String addWhere(VMember vMember, String hql, List<Object> values) {
		if (vMember.getTid() != null) {
			hql += " and t.memberType.id=? ";
			values.add(vMember.getTid());
		}
		if (vMember.getSerial() != null) {
			hql += " and t.serial = ? ";
			values.add(vMember.getSerial());
		}
		if (vMember.getCtId() != null) {
			hql += " and t.customerType = ? ";
			values.add(vMember.getCtId());
		}
		return hql;
	}

}
